package com.izhar.answeringmachine.service.Impl;

import com.izhar.answeringmachine.Entity.SubmitResult;
import com.izhar.answeringmachine.service.IWriteToFile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author izhar
 */
@Service
@Slf4j
public class WriteToFileImpl implements IWriteToFile {

    /**
     * base目录  用户方面更换windows和linux系统下的用户代码存放路径
     */
    @Value("${question.filePath}")
    private String baseLocation;

    @Override
    public void write(String userId, String questionId, String code, SubmitResult submitResult) {

        String location  =baseLocation+userId+"_"+questionId+"\\";
        //创建唯一目录，用户id+题目id
        File directory = new File(location);
        //不存在创建目录
        if (!directory.exists()){
            boolean mkdirs = directory.mkdirs();
            if (!mkdirs){
                log.error("User code directory Creation failed!!!");
                throw new RuntimeException("User code directory Creation failed!!!");
            }
        }

        //两次文件新建，中间停歇一下
        try {
            Thread.sleep(700);
        } catch (InterruptedException e) {
            log.error("User directory creation completed, system sleep error");
            throw new RuntimeException("User directory creation completed, system sleep error");
        }

        location ="D:\\1\\"+userId+"_"+questionId+"/Question.java";
        //生成Java文件
        File file = new File(location);
        if (!file.exists()){
            boolean file1 = false;
            try {
                file1 = file.createNewFile();
            } catch (IOException e) {
                log.error("Java file create，io exception: "+e.getMessage());
                throw new RuntimeException("Java file create，io exception: "+e.getMessage());
            }
            if (!file1){
                log.error("Java file create error!!!");
                throw new RuntimeException("Java file create error!!!");
            }

        }

        //写入用户代码
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            out.write(code.getBytes());
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            log.error("FileNotFoundException: "+e);
            throw new RuntimeException("FileNotFoundException: "+e);
        } catch (IOException e) {
            log.error("User code writing file io exception: "+e);
            throw new RuntimeException("User code writing file io exception: "+e);
        }
    }
}
